#include <stdio.h>
#include "My_Flash.h"

#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"

/*******************************************/
esp_err_t Flash_Init() {
    esp_err_t err = nvs_flash_init();
 
   if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    
    return err;
}

/*******************************************/
esp_err_t nvs_read(const char *key , char *out_value , size_t *length) {
    nvs_handle_t my_handle;
    esp_err_t err = nvs_open("storage", NVS_READWRITE, &my_handle);

    if (err != ESP_OK) return err;

    err = nvs_get_str(my_handle,key ,out_value , length);
    nvs_close(my_handle);
    return err;
}

/*******************************************/
esp_err_t nvs_write(const char *key , char *value) {

    nvs_handle_t my_handle;
    esp_err_t err = nvs_open("storage", NVS_READWRITE, &my_handle);

    if (err != ESP_OK) return err;

    nvs_set_str(my_handle , key , value);
    nvs_close(my_handle);

    return err;
}
